from dtos.result import Result


class SessionWrapper(object):
    @staticmethod
    def add(session, model):
        _transaction = True
        if not session.is_active:
            _transaction = False
            session.begin(subtransactions=True)
        try:
            session.add(model)
            if session.is_active and _transaction:
                session.flush()
            else:
                session.commit()
            return Result.success_result(message="创建成功")
        except Exception as ex:
            session.rollback()
            return Result.error_result(message="往数据库中插入数据时失败，原因：%s" % str(ex))

    @staticmethod
    def update(cls, session, guid, kwargs):
        session.begin(subtransactions=True)
        try:
            session.query(cls).filter(
                getattr(cls, "guid") == guid
            ).update(kwargs)
            session.commit()
            return Result.success_result(message="更新成功")
        except Exception as ex:
            session.rollback()
            return Result.error_result(message="往数据库中更新数据时失败，原因：%s" % str(ex))

    @staticmethod
    def update_all(cls, session, conditions, kwargs, message="更新成功"):
        session.begin(subtransactions=True)
        try:
            session.query(cls).filter(
                *conditions
            ).update(kwargs)
            session.commit()
            return Result.success_result(message=message)
        except Exception as ex:
            session.rollback()
            return Result.error_result(message="往数据库中更新数据时失败，原因：%s" % str(ex))
